#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
//函数外全局变量定义

int bird_x, bird_y;					//小鸟位置
int high, width;					//游戏画面尺寸
int score;							//游戏得分
int bar_y, bar_xTop, bar_xDown, bar_yy, bar_xxTop, bar_xxDown;		//障碍物坐标

void gotoxy(int x, int y)
{
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition(handle, pos);
}

void HideCursor()
{
	CONSOLE_CURSOR_INFO cursor_info = { 1,0 };//第二个值为0表示隐藏光标
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

void startup()						//数据初始化
{
	high = 16;
	width = 25;

	bird_x = high/2;
	bird_y = width / 4;

	bar_y = width;
	bar_xTop = high / 4;
	bar_xDown = high / 2+2;

	bar_yy = width / 2;
	bar_xxTop = high / 4;
	bar_xxDown = high / 2 + 2;

	score = 0;

	HideCursor(); //隐藏光标
}

void show()    //显示画面
{
	gotoxy(0, 0);					//光标移动到原点
	int i, j;
	for (i = 0; i <= high+1; i++)
	{
		for (j = 0; j <= width; j++)
		{
			if ((i == bird_x) && (j == bird_y))
				printf("@");		//输出小鸟
			else if ((j == bar_y) && (i <= bar_xTop || i >= bar_xDown))
				printf("*");
			else if ((j == bar_yy) && (i <= bar_xxTop || i >= bar_xxDown))
				printf("*");		//输出障碍物
			else
				printf(" ");		//输出空格
		}
		printf("\n");
	}
	printf("score: %d \n", score);
}

void updateWithoutInput()		//与用户输入无关的更新
{
	if (bird_y == bar_y)
	{
		if (bird_x > bar_xTop && bird_x < bar_xDown)
			score++;
		else
		{
			exit(0);
		}
	}
	if (bird_y == bar_yy)
	{
		if (bird_x > bar_xxTop && bird_x < bar_xxDown)
			score++;
		else
		{
			exit(0);
		}
	}
	if (bird_x == high)
		exit(0);

	bird_x++;

	if (bar_y > 0)
	{
		bar_y--;
	}
	else
	{
		bar_y = width;

		int randPosition = rand() % (high - 5);
		bar_xTop = randPosition;
		bar_xDown = randPosition + high / 4+2;
	}
	if (bar_yy > 0)
	{
		bar_yy--;
	}
	else
	{
		bar_yy = width;

		int randPosition = rand() % (high - 5);
		bar_xxTop = randPosition;
		bar_xxDown = randPosition + high / 4 + 2;
	}


	Sleep(150);
}
void updateWithInput()			//与用户输入有关的更新
{
	int i = 1;
	char input;
	if (kbhit())		//当按键时执行
	{
		input = getch();
		if (input == ' ')
			bird_x = bird_x - 3;
	}
}

int main()
{
	startup();
	while (1)
	{
		show();					//显示画面
		updateWithoutInput();	//与用户输入无关的更新
		updateWithInput();		//与用户输入有关的更新
	}
	return 0;
}